﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using SMSAssistant.Model;
using Microsoft.Phone.Shell;
using SMSAssistant.Resources;

namespace SMSAssistant
{
    public partial class NewMessageView : PhoneApplicationPage
    {
        enum ViewType
        {
            INIT,
            SEND,
        }

        List<Emoji> emojis;
        ApplicationBarIconButton appBarEmojiButton;
        SmsComposeTask smsTask;
        MessageDataContext msgDB;
        PhoneNumberChooserTask numberChooserTask;
        Message message;
        Message msgToSend;
        Contact contact;
        bool isNew;

        public NewMessageView()
        {
            InitializeComponent();

            message = new Message
            {
                Contact = contact
            };

            numberChooserTask = new PhoneNumberChooserTask();


            ApplicationTitle.Content = Resource.ChooseContact;

            Loaded += new RoutedEventHandler(NewMessageView_Loaded);

            msgDB = new MessageDataContext(MessageDataContext.DBConnectionString);

            //if (PhoneApplicationService.Current.State.ContainsKey("STATUS"))
            //    PhoneApplicationService.Current.State.Add("STATUS", ViewType.INIT);
        }

        void NewMessageView_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationContext.QueryString.ContainsKey("id"))
            {
                var id = int.Parse(NavigationContext.QueryString["id"]);
                message = msgDB.Messages.FirstOrDefault(m => m.Id == id);
                if (message != null)
                {
                    ApplicationTitle.Content = message.Contact.DisplayName;
                    if (string.IsNullOrEmpty(message.Content))
                        ContentPanel.Text = string.Empty;
                    else
                        ContentPanel.Text = message.Content;
                }
                BuildApplicationBar();
                ContentPanel.SelectionStart = ContentPanel.Text.Length;
                ContentPanel.Focus();

                if (EmojiManager.Instance.IsLoaded)
                    emojis = EmojiManager.Instance.EmojiList;
                else
                {
                    EmojiManager.Instance.EmojiLoaded += new EventHandler(Instance_EmojiLoaded);
                    EmojiManager.Instance.Load();
                }
            }
            else
            {
                isNew = true;
                numberChooserTask.Completed += new EventHandler<PhoneNumberResult>(numberChooserTask_Completed);
                numberChooserTask.Show();
            }
        }

        //for save mesage
        void numberChooserTask_Completed(object sender, PhoneNumberResult e)
        {
            numberChooserTask.Completed -= new EventHandler<PhoneNumberResult>(numberChooserTask_Completed);

            //throw new NotImplementedException();
            if (e.Error == null && e.TaskResult == TaskResult.OK)
            {
                var contact = msgDB.Contacts.FirstOrDefault((c) => c.DisplayName == e.DisplayName && c.PhoneNumber == e.PhoneNumber);
                if (contact == null)
                {
                    contact = new Contact
                    {
                        DisplayName = e.DisplayName,
                        PhoneNumber = e.PhoneNumber
                    };
                    msgDB.Contacts.InsertOnSubmit(contact);
                }
                ApplicationTitle.Content = contact.DisplayName;
                message.Contact = contact;
                ContentPanel.Focus();
            }

            if (EmojiManager.Instance.IsLoaded)
                emojis = EmojiManager.Instance.EmojiList;
            else
            {
                EmojiManager.Instance.EmojiLoaded += new EventHandler(Instance_EmojiLoaded);
                EmojiManager.Instance.Load();
            }

            BuildApplicationBar();
        }

        //for send message
        void numberChooserTask_Completed1(object sender, PhoneNumberResult e)
        {
            //throw new NotImplementedException();
            if (e.Error == null && e.TaskResult == TaskResult.OK)
            {
                var contact = msgDB.Contacts.FirstOrDefault((c) => c.DisplayName == e.DisplayName && c.PhoneNumber == e.PhoneNumber);
                if (contact == null)
                {
                    contact = new Contact
                    {
                        DisplayName = e.DisplayName,
                        PhoneNumber = e.PhoneNumber
                    };
                    msgDB.Contacts.InsertOnSubmit(contact);
                }

                var msgToSend = message.Clone();
                msgToSend.Contact = contact;
                msgToSend.Content = ContentPanel.Text;
                msgToSend.Category = Category.OUT;
                ApplicationTitle.Content = contact.DisplayName;

                smsTask = new SmsComposeTask
                {
                    Body = msgToSend.Content,
                    To = contact.PhoneNumber
                };

                smsTask.Show();

                msgDB.Messages.InsertOnSubmit(msgToSend);
                msgDB.SubmitChanges();

                //PhoneApplicationService.Current.State["STATUS"] = ViewType.SEND;
                //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                //ContentPanel.Focus();
            }
            else
            {
                MessageBox.Show(e.Error.Message, Resource.ErrorMessgeBoxTitle, MessageBoxButton.OK);
            }
        }

        private void ApplicationBarIconButton_save(object sender, EventArgs e)
        {
            //Clipboard.SetText(string.Empty);
            message.Content = ContentPanel.Text;
            message.CreateTime = DateTime.UtcNow;
            message.LastReviewTime = DateTime.UtcNow;
            if (message.Id == 0)
                msgDB.Messages.InsertOnSubmit(message);
            //var change = msgDB.GetChangeSet();
            msgDB.SubmitChanges();
            //PhoneApplicationService.Current.State["AUTO_NAVIGATE"] = false;

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void ApplicationBarIconButton_send(object sender, EventArgs e)
        {
            //PhoneApplicationService.Current.State["AUTO_NAVIGATE"] = false;

            //this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            if (message.Contact != null)
            {
                msgToSend = message.Clone();
                msgToSend.Content = ContentPanel.Text;
                msgToSend.Category = Category.OUT;
                //ApplicationTitle.Content = Resource.FromMeTo + " " + contact.DisplayName;

                smsTask = new SmsComposeTask
                {
                    Body = msgToSend.Content,
                    To = msgToSend.Contact.PhoneNumber
                };

                smsTask.Show();

                msgDB.Messages.InsertOnSubmit(msgToSend);
                msgDB.SubmitChanges();
            }
            else
            {
                numberChooserTask.Completed -= numberChooserTask_Completed;
                numberChooserTask.Completed += numberChooserTask_Completed1;
                numberChooserTask.Show();
            }
        }


        private void appBarEmojiButton_emoji(object sender, EventArgs e)
        {
            
            emojiList.ItemsSource = emojis;
            emojiList.Visibility = System.Windows.Visibility.Visible;
            appBarEmojiButton.Click -= appBarEmojiButton_emoji;
            appBarEmojiButton.Click += appBarEmojiButton_emoji1;

            Deployment.Current.Dispatcher.BeginInvoke(() => { emojiList.Focus(); });
        }

        private void appBarEmojiButton_emoji1(object sender, EventArgs e)
        {
            ContentPanel.Select(ContentPanel.Text.Length, 0);
            ContentPanel.Focus();
            emojiList.Visibility = System.Windows.Visibility.Collapsed;
            appBarEmojiButton.Click += appBarEmojiButton_emoji;
            appBarEmojiButton.Click -= appBarEmojiButton_emoji1;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);

            if (msgToSend != null || !isNew)
                return;

            var result = MessageBox.Show(Resource.ConfirmToDiscardMessage, string.Empty, MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {

            }
            else
            {
                e.Cancel = true;
            }
        }

        private void ApplicationTitle_Click(object sender, RoutedEventArgs e)
        {
            numberChooserTask.Completed += new EventHandler<PhoneNumberResult>(numberChooserTask_Completed);
            numberChooserTask.Show();
        }

        private void BuildApplicationBar()
        {
            //shell:ApplicationBarIconButton IconUri="/Images/AppBarIcons/appbar.save.rest.png" Click="ApplicationBarIconButton_save"  Text="save"/>
            //shell:ApplicationBarIconButton Click="ApplicationBarIconButton_cancel" IconUri="/Images/AppBarIcons/delete.png" Text="cancel"/>
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar() { Opacity = .5 };

            // Create a new button and set the text value to the localized string from AppResources.
            ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar.save.rest.png", UriKind.Relative));
            appBarButton.Click += ApplicationBarIconButton_save;
            appBarButton.Text = Resource.Save;
            ApplicationBar.Buttons.Add(appBarButton);

            // Create a new button and set the text value to the localized string from AppResources.
            appBarEmojiButton = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/ApplicationIcon_Expression.png", UriKind.Relative));
            appBarEmojiButton.Click += appBarEmojiButton_emoji;
            appBarEmojiButton.Text = Resource.Send;
            ApplicationBar.Buttons.Add(appBarEmojiButton);

            // Create a new button and set the text value to the localized string from AppResources.
            ApplicationBarIconButton appBarSendButton = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar.messaging.rest.png", UriKind.Relative));
            appBarSendButton.Click += ApplicationBarIconButton_send;
            appBarSendButton.Text = Resource.Send;
            ApplicationBar.Buttons.Add(appBarSendButton);

            //// Create a new menu item with the localized string from AppResources.
            //ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(Resource.PinToStart);
            //appBarMenuItem.Click += ApplicationBarIconButton_cancel;
            //ApplicationBar.MenuItems.Add(appBarMenuItem);

            //// Create a new menu item with the localized string from AppResources.
            //ApplicationBarMenuItem appBarMenuItem2 = new ApplicationBarMenuItem(Resource.BackupMenuItemLabel);
            //appBarMenuItem2.Click += ApplicationBarMenuItem2_Click;
            //ApplicationBar.MenuItems.Add(appBarMenuItem2);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        void Instance_EmojiLoaded(object sender, EventArgs e)
        {
            EmojiManager.Instance.EmojiLoaded -= Instance_EmojiLoaded;
            emojis = EmojiManager.Instance.EmojiList;
            //throw new NotImplementedException();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var obj = sender as Button;

            if (obj != null)
            {
                var emoji = obj.DataContext as Emoji;
                if (emoji != null)
                {
                    ContentPanel.Text = ContentPanel.Text + emoji.Tag;
                    obj.Focus();
                }
            }
        }
    }
}